package com.gopay.cashier.web.controller.T00100;

import com.alibaba.fastjson.JSON;
import com.gopay.cashier.common.exception.WebException;
import com.gopay.cashier.web.command.OrderInfo;
import com.gopay.cashier.web.controller.BaseController;
import com.gopay.cashier.web.utils.CashierConfig;
import com.gopay.cashier.web.utils.PayPwdQuestionsInfo;
import com.gopay.common.constants.cust.CustPersonInfoConstants;
import com.gopay.common.constants.cust.RealNameCertifyStep;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.constants.trans.TxnStaCode;
import com.gopay.common.constants.txncd.IntTxnCd;
import com.gopay.common.domain.cps.CpsGenMainOrder;
import com.gopay.common.domain.cust.CustPersonInfo;
import com.gopay.common.log.annotation.LogX;
import com.gopay.common.log.collect.LogBag;
import com.gopay.common.log.collect.LogBagUtil;
import com.gopay.common.log.constants.LogOperStatusCd;
import com.gopay.common.log.logxnew.constants.LogCodeConstants;
import com.gopay.common.user.manager.DicCustProfessionQueryManager;
import com.gopay.common.util.NonrevEncr;
import com.gopay.remote.acps.service.AcctTransRemoteService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.Date;

/**
 * Created by HJY on 2015/5/13.
 */
@Controller
@RequestMapping("/user")
public class UserInfoSupportController extends BaseController{

    @Resource(name="dicCustProfessionQueryManager")
    private DicCustProfessionQueryManager dicCustProfessionQueryManager;

    @Resource(name="doTransService")
    protected AcctTransRemoteService doTransService;

    private static final String PORTAL_URL = CashierConfig.get(CashierConfig.PORTAL_URL);

    @RequestMapping("/complete")
    public ModelAndView completeUserInfo(String orderId,String custId,String type)  throws WebException {
        printRequest("userInfoSupportController--completeUserInfo");
        ModelAndView mv = new ModelAndView();
        CpsGenMainOrder order = getMainOrder(orderId, true);
        if (TxnStaCode.TXN_STA_CD_20000.value != (order.getTxnStaCd())) {
            logger.error("订单状态不对！txn_sta_cd wrong!" + order);
            throw new WebException(ProcCodeConstants.PROC_CODE_100E5042);
        }
        mv.addObject("portalUrl",PORTAL_URL);
        CustPersonInfo  custInfo =  custPersonInfoQueryManager.get(custId);
        if(custInfo != null){
            OrderInfo orderInfo = getOrderInfo(orderId);
            mv.addObject("order",orderInfo);
            mv.addObject("custId",custId);
            mv.addObject("orderId",orderId);
            if(StringUtils.equals(custInfo.getCustStat(), CustPersonInfoConstants.CUST_STAT_NORMAL) && StringUtils.isBlank(custInfo.getPayPwd())){
                mv.setViewName("00100/content/express/completeInfo");
                mv.addObject("profession", dicCustProfessionQueryManager.getAll());//职业
                mv.addObject("questionList", PayPwdQuestionsInfo.getNewQuestionList());//问题
                mv.addObject("type",type);
            }else if(StringUtils.equals(custInfo.getCustStat(), CustPersonInfoConstants.CUST_STAT_NORMAL)  && StringUtils.isNotBlank(custInfo.getPayPwd())){
                //已补全
                mv.setViewName("00100/content/express/completeTip");
            }else{
                //状态不正常
                throw new WebException(ProcCodeConstants.PROC_CODE_100E2002);
            }
        }else{
            //用户不存在
            throw new WebException(ProcCodeConstants.PROC_CODE_100E2001);
        }
        return mv;
    }

    @LogX(operTypeCd = LogCodeConstants.CASHIER_CUST_BASICINFO_01)
    @RequestMapping(value = "/submit",method = RequestMethod.POST)
    public ModelAndView submit(String custIdNoUse,String custProession,String payPassWd,String pwdQuestion,String pwdAnswer) throws WebException {
        printRequest("userInfoSupportController--submit");
        if( StringUtils.isBlank(custProession) || StringUtils.isBlank(payPassWd) || StringUtils.isBlank(pwdQuestion) || StringUtils.isBlank(pwdAnswer)){
            logger.error("complete cust info data is null----");
            throw new WebException(ProcCodeConstants.PROC_CODE_100E2001);
        }
        // 此处为原订单号
        String orderId = getRequest().getParameter(GOPAY_ORDER_ID);
        CpsGenMainOrder order = getMainOrder(orderId, true);
        if(StringUtils.equals(getRequest().getParameter("type"),"2")){
            if (TxnStaCode.TXN_STA_CD_30000.value != (order.getTxnStaCd())) {
                logger.error("订单状态不对！txn_sta_cd wrong!" + order);
                throw new WebException(ProcCodeConstants.PROC_CODE_100E5042);
            }
        }else{
            if (TxnStaCode.TXN_STA_CD_20000.value != (order.getTxnStaCd())) {
                logger.error("订单状态不对！txn_sta_cd wrong!" + order);
                throw new WebException(ProcCodeConstants.PROC_CODE_100E5042);
            }
        }
        // custId不通过参数传递，通过session获取  20160912  dak.wang
        String custId = (String) getRequest().getSession().getAttribute("fillInfoCustId");

        CustPersonInfo cpi = custPersonInfoQueryManager.get(custId);
        if(cpi == null) {
            throw new WebException(ProcCodeConstants.PROC_CODE_100E2001);
        }

        // LogX记录日志 20160927 add by XuHui
        LogBag logBag = getLogBag(cpi);
        logBag.setOrderId(orderId);

        ModelAndView mv = new ModelAndView("00100/content/express/completeTip");
        mv.addObject("portalUrl",PORTAL_URL);
        /**
		 * modified by zyt, 使用sha512处理
		 * 2017-1-13
		 */
        //start++++++++++
        cpi.setPayPwd(NonrevEncr.sha512(new StringBuilder(custId).append(payPassWd)));
        String vQues = NonrevEncr.sha512(new StringBuilder(custId.trim()).append(pwdQuestion.trim()));
        String vAnswer = NonrevEncr.sha512(new StringBuilder(custId.trim()).append(pwdAnswer.trim()));
       /* cpi.setPayPwd(NonrevEncr.sha1(custId + payPassWd));
        String vQues = NonrevEncr.sha1((custId + pwdQuestion).trim());
        String vAnswer = NonrevEncr.sha1((custId + pwdAnswer).trim());*/
        //end++++++++
        cpi.setCustStat(CustPersonInfoConstants.CUST_STAT_NORMAL);
        cpi.setPayQus(vQues);
        cpi.setPayQusAnswer(vAnswer);
        if (TxnStaCode.TXN_STA_CD_20000.value == order.getTxnStaCd() && ((StringUtils.equals(order.getPayCustId(),custId) && StringUtils.equals(order.getGopayIntTxnCd(), IntTxnCd._00100.value)))) {
            //支付成功，更新用户实名
            cpi.setIsMobileCertify(CustPersonInfoConstants.MOBILE_CERTIFY_YES);//手机认证
            cpi.setIsRealNameCertify(CustPersonInfoConstants.REAL_NAME_CERTIFY_HALF);//实名认证
        }

        cpi.setCustProession(custProession);//职业
        cpi.setPayPwdStatus(0);
        cpi.setPayQusAnsStatus(0);
        cpi.setTodayPwdErrNum(0);
        cpi.setTotalPwdErrNum(0);
        cpi.setTotalPwdQusErrNum(0);
        cpi.setLastUpdTs(new Date());//更新时间
        
        // dak.wang 20160527 start
        if (CustPersonInfoConstants.REAL_NAME_CERTIFY_NO.equals(cpi.getIsRealNameCertify())) {
            cpi.setRealNameCertifyStep(RealNameCertifyStep.REAL_NAME_CERTIFY_STEP_12B.value);
        }  else if (CustPersonInfoConstants.REAL_NAME_CERTIFY_HALF.equals(cpi.getIsRealNameCertify())) {
            if (RealNameCertifyStep.REAL_NAME_CERTIFY_STEP_12.value.equals(cpi.getRealNameCertifyStep())) {
                cpi.setRealNameCertifyStep(RealNameCertifyStep.REAL_NAME_CERTIFY_STEP_20.value);
            } else {
                cpi.setRealNameCertifyStep(RealNameCertifyStep.REAL_NAME_CERTIFY_STEP_11.value);
            }
        }   else if (CustPersonInfoConstants.REAL_NAME_CERTIFY_YES.equals(cpi.getIsRealNameCertify())) {
            cpi.setRealNameCertifyStep(RealNameCertifyStep.REAL_NAME_CERTIFY_STEP_00.value);
        } 
        // end
        userRemoteService.editCustPersonUser(cpi);
        logBag.setSnapshotAfter(JSON.toJSONString(cpi));
        logBag.setStatus(LogOperStatusCd.SUCCESS.value);
        
     // 根据客户ID查询账户列表
        // 根据央行检测支付账户改造，完善资料后暂不生成账户   dak.wang 20160523
        /*List<AcctMastBean> acctList = doTransService.getAccounts(custId);
        logger.info("快捷支付成功创建账户--开始，custId="+custId+",acctList.size="+(acctList!=null?acctList.size():0));
        if(acctList==null||acctList.size()==0){
        	TranResult tr = doTransService.createAccount(AcctMastType.PERSON,
            		custId, "普通账户", SchemaCode.SCHEMA_CODE_2011, AcctProd.GNST,
            		CurrencyCode.CNY, "快捷支付");
            
        	logger.info("快捷支付成功创建账户--结束，custId="+custId+",result="+tr.isSuccess());
        	
        }*/

        if(StringUtils.equals(getRequest().getParameter("type"),"2")){
            //登录后补充完信息，跳转支付界面
            mv.setViewName("redirect:/sec/pay/info.shtml?orderKey="+getRequest().getParameter("orderKey")+"&orderId="+orderId);
        }
        return mv;
    }

    private LogBag getLogBag(CustPersonInfo cpi) {
        LogBag logBag = LogBagUtil.get();
        logBag.setLaunchUserId(cpi.getOperId());
        logBag.setLaunchUserName(cpi.getCustName());
        logBag.setLaunchCustId(cpi.getCustId());
        logBag.setLaunchCustName(cpi.getCustName());
        logBag.setTargetCustId(cpi.getCustId());
        logBag.setTargetCustName(cpi.getCustName());
        logBag.init(getRequest());
        logBag.setSnapshotBefore(JSON.toJSONString(cpi));
        return logBag;
    }
}
